<template>
  <BasicModal
    :visible="visible"
    :title="title"
    :min-height="modalHeight"
    :height="modalHeight"
    :show-ok-btn="true"
    :show-cancel-btn="true"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form ref="form" :model="formData">
      <a-form-item label="名称" name="name" :rules="[{ required: true }]">
        <a-input v-model:value="formData.name" :disabled="disableName" />
      </a-form-item>
      <a-form-item label="描述" name="desc" :rules="[{ required: true }]">
        <a-input v-model:value="formData.desc" />
      </a-form-item>
      <a-form-item v-if="showAppAndSpace" label="应用" name="app" :rules="[{ required: true }]">
        <a-input v-model:value="formData.app" />
      </a-form-item>
      <a-form-item v-if="showAppAndSpace" label="空间" name="space" :rules="[{ required: true }]">
        <a-input v-model:value="formData.space" />
      </a-form-item>
    </a-form>
  </BasicModal>
</template>

<script>
  import { Form, FormItem, Input } from 'ant-design-vue'
  import { BasicModal } from '/@/components/Modal'
  import { useModuleStoreWithOut } from '/@/store/modules/module'

  export default {
    components: {
      'a-input': Input,
      'a-form': Form,
      'a-form-item': FormItem,
      BasicModal,
    },
    props: {
      visible: Boolean,
      title: String,
    },
    emits: ['ok', 'cancel'],
    data: function () {
      return {
        store: useModuleStoreWithOut(),
        formData: {
          id: 0,
          name: '',
          desc: '',
          app: '',
          space: '',
          parentId: 0,
          parentName: '',
          createType: 'manual',
          moduleType: 'system', // means non-service module
        },
      }
    },
    computed: {
      disableName() {
        return this.store.getParent.name === 'none'
      },
      showAppAndSpace() {
        return this.store.getParent.name === 'none'
      },
      modalHeight() {
        return this.store.getParent.name === 'none' ? 220 : 120
      },
    },
    watch: {
      'formData.app': function (newVal) {
        this.formData.name = newVal + '.' + this.formData.space
      },
      'formData.space': function (newVal) {
        this.formData.name = this.formData.app + '.' + newVal
      },
    },
    mounted() {
      this.formData.app = this.store.getRoot.app
      this.formData.space = this.store.getRoot.space
      this.formData.parentName = this.store.getParent.name
      this.formData.parentId = this.store.getParent.id
    },
    methods: {
      handleCancel() {
        this.$emit('cancel')
      },
      handleOk() {
        this.$refs.form
          .validate()
          .then(() => {
            this.$emit('ok', this.formData)
          })
          .catch((error) => {
            console.log('error', error)
          })
      },
    },
  }
</script>
